package com.stylefeng.guns.modular.pay.controller;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.modular.pay.model.WithdrawOrder;
import com.stylefeng.guns.modular.pay.service.AllInPayService;
import com.stylefeng.guns.modular.pay.service.IWithdrawOrderService;
import com.stylefeng.guns.modular.pay.service.impl.WithdrawApplyServiceImpl;

@Controller
@RequestMapping("/api")
public class AllInPayNotifyController extends BaseController{
    private final static Logger logger = LoggerFactory.getLogger(AllInPayNotifyController.class);
    @Autowired
    private AllInPayService allInPayService;
    @Autowired
    private IWithdrawOrderService withdrawOrderService;
	 /**
     * 异步成功通知
     * @param requestO
     * @return
     * @throws Exception
     */
    @RequestMapping("/notify/success")
    public void notifySuccess(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	PrintWriter writer = null;
    	try {
    		writer = response.getWriter();
    		Map<String,String> params = getRequestParams(request);
    		logger.info("【代付】成功异步通知参数:"+params);
        	String plateTradeNo = params.get("BATCHID");
        	WithdrawOrder order = withdrawOrderService.selectOne(new EntityWrapper<WithdrawOrder>().eq("plat_trade_no", plateTradeNo));
			if(order==null){
				throw new RuntimeException("订单不存在");
			}
			allInPayService.notify(params,order);
			writer.write("SUCCESS");
			writer.flush();
    	} catch (Exception e) {
    		writer.write("ERROR");
			writer.flush();
			writer.close();
		}
    }
    
    /**
     * 异步失败通知
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/notify/fail")
    public void notifyFail(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	PrintWriter writer = null;
    	try {
    		writer = response.getWriter();
    		Map<String,String> params = getRequestParams(request);
    		logger.info("【代付】失败异步通知参数:"+params);
        	String plateTradeNo = params.get("BATCHID");
        	WithdrawOrder order = withdrawOrderService.selectOne(new EntityWrapper<WithdrawOrder>().eq("plat_trade_no", plateTradeNo));
			if(order==null){
				throw new RuntimeException("订单不存在");
			}
			allInPayService.notify(params,order);
			
			writer.write("SUCCESS");
			writer.flush();
    	} catch (Exception e) {
    		writer.write("ERROR");
			writer.flush();
			writer.close();
		}
    }

}
